<template>
  <div class="login">
    <van-nav-bar
  title="账号登录"
  left-arrow
  @click-left="$router.push('/home')"
  />
  <van-form @submit="onSubmit">
  <van-field
    v-model="userInfo.username"
    name="用户名"
    placeholder="请输入账号"
  />
  <van-field
    v-model="userInfo.password"
    type="password"
    name="密码"
    placeholder="请输入密码"
  />

  <div style="margin: 16px;">
    <van-button  block type="info" native-type="submit" :loading='loading' :disabled='loading'>登录</van-button>
  </div>
</van-form>

<router-link to="/register">还没有账号，去注册~</router-link>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      userInfo: {
        username: 'admin',
        password: 'admin'
      },
      // 登录按钮加载
      loading: false,
      timer: null

    }
  },
  // created() {
  //   // if (window.localStorage.getItem('TOKEN') === '') this.$Toast.fail('您还没有登录哦')
  //   // console.log(this.$route)
  // },
  methods: {
    // 表单提交按钮
    async onSubmit () {
      this.loading = true
      const reg = /^[a-zA-Z0-9]{5,8}$/
      if (!this.userInfo.username.trim() || !this.userInfo.password.trim()) {
        this.loading = false
        return this.$Toast('账号和密码不能为空')
      }
      if (!reg.exec(this.userInfo.username) || !reg.exec(this.userInfo.password)) {
        this.loading = false
        return this.$Toast('请输入5-8位字母和数字')
      }
      try {
        await this.$store.dispatch('confirmLogin', this.userInfo)
        this.$Toast.success('登录成功')
        this.timer = setTimeout(() => {
          // console.log(this.$route)
          this.$router.replace({
            path: this.$route.query.path || '/home'
          })
        }, 500)
        this.$once('hook:beforeDestroy', () => {
          // 清除定时器
          clearInterval(this.timer)
        })
      } catch (error) {
        this.$Toast.fail('你的账号或密码异常')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-nav-bar .van-icon{
  color: #fff;
}
/deep/ .van-button--info {
    background-color: #43b978;
    border: 0.02667rem solid #43b978;
}
.van-field{
  height: 60px;
  font-size: 17px;
  padding: 0 20px ;
  width: 100%;
  margin: 20px 0;
}
.van-cell{
  line-height:60px;
}
/deep/ .van-cell::after{
  border-bottom: 0.02667rem solid #c7d2e0
}
.van-button{
    font-size: 18px;
    height: 50px;
    line-height: 50px;
    margin-bottom: 20px;
}

.login{
  text-align: center;
      a{
     font-size: 14px;
      color: #666;
    }
}

</style>
